# $1: toolchain path

LIBS_DIR=libs
BOOTNAME=bootloader

TOOLCHAIN_BASE=$1
CLANG_BIN=${TOOLCHAIN_BASE}/bin/clang.bin
AS_BIN=${TOOLCHAIN_BASE}/bin/as.bin
LD_BIN=${TOOLCHAIN_BASE}/bin/ld.bin

DRIVERLIB_DIR=../${LIBS_DIR}/driverlib
CSRC_GLOBALVARIABLEDEFS=${DRIVERLIB_DIR}/globalvariabledefs.c
CSRC_MAIN=bootloadermain.c
SSRC_STARTUP=bootloaderstartup.s

OPTIMIZE_LEVEL=0
CLANG_FLAGS="-c -gdwarf-2 -target dsp -mcpu=qx320f -ffunction-sections -fdata-sections -O${OPTIMIZE_LEVEL}"
CLANG_INCLUDE="-I${TOOLCHAIN_BASE}/include -I../${LIBS_DIR}/device -I${DRIVERLIB_DIR} -I${DRIVERLIB_DIR}/bit_field"
AS_FLAGS="-g --gdwarf-2"
LD_LIB_PATH="-L../${LIBS_DIR}/ldscript -Lldscript -L${TOOLCHAIN_BASE}/lib"

RELEASE_DIR=Release
LD_FLAGS="-T ldscript_BootLoader.ld -Map=${RELEASE_DIR}/linkMapFile --no-check-sections --gc-sections"
OBJ_GLOBALVARIABLEDEFS=${RELEASE_DIR}/globalvariabledefs.o
OBJ_MAIN=${RELEASE_DIR}/bootloadermain.o
OBJ_STARTUP=${RELEASE_DIR}/bootloaderstartup.o
OUT_EXECUTABLE=${RELEASE_DIR}/${BOOTNAME}.out

echo Building bootloader ... 
[ ! -d ${RELEASE_DIR} ] && mkdir ${RELEASE_DIR}
${CLANG_BIN} ${CLANG_FLAGS} ${CLANG_INCLUDE} ${CSRC_GLOBALVARIABLEDEFS} -o ${OBJ_GLOBALVARIABLEDEFS}
${CLANG_BIN} ${CLANG_FLAGS} ${CLANG_INCLUDE} ${CSRC_MAIN} -o ${OBJ_MAIN}
${AS_BIN} ${AS_FLAGS} ${SSRC_STARTUP} -o ${OBJ_STARTUP}
${LD_BIN} ${LD_LIB_PATH} ${LD_FLAGS} ${OBJ_GLOBALVARIABLEDEFS} ${OBJ_MAIN} ${OBJ_STARTUP} -o ${OUT_EXECUTABLE}
echo done.

cd ${RELEASE_DIR}
python3 $1/bin/gen_ram_image.py --coretype bootloader --inputexec ${BOOTNAME}.out --toolbinpath $1/bin --linux
cd - > /dev/null
